package filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import bean.Goods;
import dao.CheckSellUserInfo;
import dao.GetGoodsCount;
import dao.ListGoods;
import dao.SelectOneUser;

/**
 * Servlet Filter implementation class UserGoodsList 获得当前用户出售的所有商品
 */
public class UserGoodsList implements Filter {

	/**
	 * Default constructor.
	 */
	public UserGoodsList() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpSession session = httpServletRequest.getSession();
		String numString = (String) session.getAttribute("usernum");// 取得session中得字段信息
		if (!CheckSellUserInfo.checkInfo(numString)) {// 判断用户信息是否完善
			request.getRequestDispatcher("/user/update.jsp").forward(request,
					response);
			return;
		}

		int id = SelectOneUser.getUserId(numString);// 根据学号查询id

		String pageString = request.getParameter("page");// 取得传来的被请求的页码
		int page = Integer.parseInt(pageString);

		int count = GetGoodsCount
				.getCount("SELECT count(*) FROM goods WHERE user_id=" + id);// 获得总页数
		int pagecount = (count - 1) / 20 + 1;
		if (page == -1 || page > pagecount)// 到达最后一页
			page = pagecount;
		if (page == 0)// 到达第一页
			page = 1;

		List<Goods> list = ListGoods
				.getListGoods("select * from goods where user_id="
						+ id
						+ " order by goods_id desc limit "+(page-1)*20+",20");

		request.setAttribute("list", list);// 将结果放入request
		request.setAttribute("page", page);
		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
